<template>
	<app-layout>
		<view class=" tn-safe-area-inset-bottom">
			<!-- 顶部自定义导航 -->
			<tn-nav-bar>{{title}}</tn-nav-bar>

			<view class="about__wrap" :style="{paddingTop: vuex_custom_bar_height + 'px'}">

				<!-- 我的信息  查看-->
				<view class="tn-padding-bottom-xl ">
					<block>
						<!-- 我的信息  编辑-->
						<view class=" ">
							<tn-form :labelWidth="180" :model="form" ref="uForm" :errorType="['message']">
								<view class="tn-bg-white tn-padding tn-margin-bottom-sm">
									<tn-form-item label="姓名" prop="xdusername">
										{{xduser.username}}
									</tn-form-item>
									<tn-form-item label="毛发编号" prop="xdusername">
										{{xduser.mfid}}
									</tn-form-item>
									<tn-form-item label="管控乡镇" prop="xdusername">
										{{xduser.gsxz}}
									</tn-form-item>
									<!-- 3.最上方显示姓名（username）、毛发编号（mfid），管控乡镇（gsxz）. -->
									<tn-form-item label="毛发袋条码" prop="qrcode" :required="true" v-if="form.isqrcode==1">
										<view class="qrcodet" v-if="!form.qrcode">请扫描条毛发袋条码</view>
										<view v-else>
											条码已记录
										</view>
										<tn-button slot="right" backgroundColor="#2074d4" fontColor="#FFFFFF"
											@click="scancode">扫码</tn-button>
									</tn-form-item>
									<!-- 取材地址 -->
									<template v-if="form.sfqc">
										<tn-form-item label="取材部位" prop="qcbw" :required="true">
											<tn-input v-model="form.qcbw" type="select" :selectOpen="positionShow"
												placeholder='选择取材部位' @click="positionShow = true" />
											<tn-select labelName="details" valueName="id" v-model="positionShow"
												:list="positionlist" @confirm="positionconfirm"></tn-select>
										</tn-form-item>
									</template>
									<!-- 未选头发时 -->
									<template v-if="form.positionid != 101 && form.positionid != ''">
										<tn-form-item label="是否光头" prop="sfgttext" :required="true">
											<tn-input v-model="form.sfgttext" type="select" :selectOpen="sfgtShow"
												placeholder='选择是否光头' @click="sfgtShow = true" />
											<tn-select labelName="name" valueName="id" v-model="sfgtShow" :list="issxlist"
												@confirm="sfgtconfirm"></tn-select>
										</tn-form-item>
										<tn-form-item label="未取原因" prop="nothair" :required="true" v-if="!form.isbare">
											<tn-input v-model="form.nothair" type="textarea" :border="!!0" :height="100"
												placeholder='请输入未取头发的原因' />
										</tn-form-item>
										<tn-form-item label="光头原因" prop="cause" :required="true" v-if="form.isbare">
											<tn-input v-model="form.cause" type="textarea" :border="!!0" :height="100"
												placeholder='请输入光头原因' />
										</tn-form-item>
									</template>
									<tn-form-item label="样本长度" prop="qccd" :required="true">
										<tn-input v-model="form.qccd" type="number" placeholder="请输入样本长度"></tn-input>
										<view slot="right">cm</view>
									</tn-form-item>

									<tn-form-item label="取材地点" prop="qydd" :required="true">
										<tn-input v-model="form.qydd" type="select" :selectOpen="addressShow"
											placeholder='选择取材地点' @click="addressShow = true" />
										<tn-select labelName="details" valueName="id" v-model="addressShow"
											:list="addresslist" @confirm="addressconfirm"></tn-select>
									</tn-form-item>

									<tn-form-item label="选择村委" prop="qyddok" v-if="form.placeid==97" :required="true">
										<tn-input v-model="form.qyddok" type="select" :selectOpen="cityShow"
											placeholder='选择村委(社区)' @click="cityShow = true" />
										<tn-select labelName="name" valueName="id" v-model="cityShow" :list="citylist"
											@confirm="cityconfirm" :searchShow="true"></tn-select>
									</tn-form-item>

									<tn-form-item label="选择城市" prop="pcaeraname" :required="true"
										v-if="form.placeid=='172'|| form.placeid=='100'|| form.placeid=='99' || form.placeid=='98'">
										<tn-input v-model="form.pcaeraname" type="select" :selectOpen="dqShow"
											placeholder='选择城市' @click="dqShow = true" />
										<tn-picker mode="region" v-model="dqShow" @confirm="dqconfirm"></tn-picker>
									</tn-form-item>
									<tn-form-item label="输入地点" prop="elaeraname" :required="true"
										v-if="form.placeid=='172'|| form.placeid=='100'|| form.placeid=='99' || form.placeid=='98'">
										<tn-input v-model="form.elaeraname" type="textarea" :border="!!0" :height="100"
											placeholder='详细地址' />
									</tn-form-item>


									<tn-form-item label="提取人" prop="tquser" :required="true">
										<tn-input v-if="form.placeid==172" :maxLength="20" v-model="form.zhanghaouser"
											type="text" placeholder='请选择提取人' />
										<view v-else class="tn-flex tn-flex-wrap">
											<tn-checkbox-group @change="userchange">
												<tn-checkbox v-model="item.checked" v-for="(item, index) in witness"
													:key="index"
													:name="item.zhanghaouser">{{item.zhanghaouser}}</tn-checkbox>
											</tn-checkbox-group>
										</view>
									</tn-form-item>

									<tn-form-item label="检测照片" prop="jczp" :required="true">
										<view @click="showloading">
											<tn-image-upload :formData="formData" :action="action" @on-error="uperror"
												uploadText="拍照上传" :isdd="isdd" :autoUpload="!!1" @on-change="upchange"
												@on-success="upsuccess" @on-choose-complete="choosecomplete"
												:showUploadList="setting.showUploadList"
												:sourceType="setting.sourceType"></tn-image-upload>
										</view>
									</tn-form-item>

									<tn-form-item label="取材时间" prop="tqtime" :required="true">
										<tn-input v-model="form.tqtime" type="select" :selectOpen="timestartShow"
											placeholder='取材时间' @click="timestartShow = true" />

									</tn-form-item>
									<!--<tn-form-item prop="address_detail">
									<tn-input v-model="address_detail" type="textarea" :border="!!1" :height="100"
										placeholder='详细地址' />
								</tn-form-item> -->

								</view>
								<view class="tn-bg-white tn-padding">
									<view class="tn-text-bold">
										尿检信息
									</view>
									<!-- <tn-form-item label="是否尿检" prop="sfnj">
										<view>{{form.sfnj?'是':'否'}}</view>
										<tn-switch slot="right" v-model="form.sfnj"></tn-switch>
									</tn-form-item> -->
									<tn-form-item label="是否尿检" prop="sfnjtext" :required="true">
										<tn-input v-model="form.sfnjtext" type="select" :selectOpen="sfnjShow"
											placeholder='选择是否尿检' @click="sfnjShow = true" />
										<tn-select labelName="name" valueName="id" v-model="sfnjShow" :list="issxlist"
											@confirm="sfnjconfirm"></tn-select>
									</tn-form-item>
									<template v-if="form.sfnj">
										<tn-form-item label="通知日期" prop="tztime" :required="true">
											<tn-input v-model="form.tztime" type="select" :selectOpen="tztime"
												placeholder='选择通知日期' @click="tztime = true" />
											<tn-calendar :safeAreaInsetBottom="!!1" :toolTips="`选择通知日期`"
												v-model="tztime" :changeYear="false" mode="date"
												@change="tzselect"></tn-calendar>
										</tn-form-item>
										<tn-form-item label="检测种类" prop="njtype" :required="true">
											<view class="tn-flex tn-flex-wrap">
												<tn-checkbox-group @change="ilkchange">
													<tn-checkbox v-model="item.checked" v-for="(item, index) in ilklist"
														:key="index" :name="item.num">{{item.details}}</tn-checkbox>
												</tn-checkbox-group>
											</view>
										</tn-form-item>
										<tn-form-item label="检测结果" prop="njresult" :required="true">
											<view v-if="ilkresult.length<1" class="tn-flex tn-flex-wrap">
												<tn-input disabled placeholder='选择检测种类' />
											</view>
											<view class="ilkresult">
												<view v-for="(res, index) in ilkresult" :key="index"
													class="tn-flex  tn-flex-col-center tn-flex-row-right">
													<template>
														<view class="nm">
															{{res.name}}
														</view>
														<view class="yx"
															:class="res.result===0 && 'tn-bg-green tn-color-white'"
															@click="setilk(index,0)">
															阴性
														</view>
														<view class="yx"
															:class="res.result===1 && 'tn-bg-red tn-color-white'"
															@click="setilk(index,1)">
															阳性
														</view>
													</template>
												</view>
											</view>
										</tn-form-item>
									</template>

								</view>

							</tn-form>
						</view>
					</block>
				</view>
			</view>

			<bottom-btn @submit="submit"></bottom-btn>

			<view class='tn-tabbar-height'></view>

		</view>
	</app-layout>
</template>

<script>
	import locationmixin from '@/libs/mixin/location_mixin.js'
	import {
		mapGetters,
		mapState
	} from 'vuex';
	export default {
		name: 'hairadd',
		mixins: [locationmixin],
		computed: {
			...mapState({
				userinfo: state => state.userinfo
			})
		},
		data() {
			return {
				title: '新增',
				timestartShow: false,
				formData: {},
				//通知时间
				tztime: false,
				// 任务信息
				taskinfo: '',
				//检查类型
				ilklist: [],
				ilkresult: [],
				//走访地点只显示村委、家中、单位、其他
				addressShow: false,
				addresslist: [],
				//村列表
				cityShow: false,
				citylist: [],
				//城市列表
				dqShow: false,
				//走访人列表
				witness: [],
				//最大可选日期
				maxday: '',
				sfgtShow: false,
				sfnjShow: false,
				issxlist: [{
					id: 1,
					name: '是'
				}, {
					id: 0,
					name: '否'
				}],
				//身体部位
				positionShow: false,
				positionlist: [],

				//未取原因
				noshow: false,
				nolist: [],

				form: {
					mfid: '',
					username: '',
					//是否取材
					sfqc: true,
					//取材部位
					qcbw: '',
					//取样地点
					qydd: '',
					// 取样详细地址
					qyddok: '',
					//是否光头
					isbare: false,
					sfgttext: '',
					//光头原因
					cause: '',
					//不是光头未取头发原因
					nothair: '',
					sfyx: 0,
					//提取人
					tquser: '',
					//尿检结果
					njtype: '',
					njresult: '',
					//样本长度
					qccd: '',
					//条形码
					qrcode: '',
					//是否尿检
					sfnj: false,
					sfnjtext: '',
					//通知时间
					tztime: '',
					//取材时间
					tqtime: '',
					//城市名称
					pcaeraname: '',
					//详细地址
					elaeraname: '',
					//地方id
					placeid: '',
					type: '',
					//身体部位
					positionid: '',
					// uploadname: '',
					// uploadtype: '',
					//检测照片
					jczp: '',
					// 任务ID
					tid: 0,
					//异地任务iD
					cid: 0,
					// 是否扫码
					isqrcode: 1
				},
				time: '',
				rules: {
					qrcode: [{
						required: true,
						message: '请扫描条毛发袋条码',
						trigger: 'blur,change'
					}],
					tztime: [{
						required: true,
						message: '请选择通知时间',
						trigger: 'blur,change'
					}],
					qydd: [{
						required: true,
						message: '请选择地点',
						trigger: 'blur,change'
					}],

					pcaeraname: [{
						required: true,
						message: '请选择城市',
						trigger: 'blur,change'
					}],
					elaeraname: [{
						required: true,
						message: '请输入详细地址',
						trigger: 'blur,change'
					}],
					qyddok: [{
						required: true,
						message: '请选择村委',
						trigger: 'blur,change'
					}],
					type: [{
						required: true,
						message: '请选择检查类别',
						trigger: 'blur,change'
					}],
					qccd: [{
						required: true,
						message: '请输入样本长度',
						trigger: 'blur,change'
					}],
					tqtime: [{
						required: true,
						message: '请选择取材时间',
						trigger: 'blur,change'
					}],
					sfnjtext: [{
						required: true,
						message: '请选择是否尿检',
						trigger: 'blur,change'
					}],
					sfgttext: [{
						required: true,
						message: '请选择是否光头',
						trigger: 'blur,change'
					}],
					qcbw: [{
						required: true,
						message: '请选择取材部位',
						trigger: 'blur,change'
					}],
					cause: [{
						required: true,
						message: '请输入光头原因',
						trigger: 'blur,change'
					}],
					jczp: [{
						required: true,
						message: '请上传检测照片',
						trigger: 'blur,change'
					}],
					nothair: [{
						required: true,
						message: '请输入未取原因',
						trigger: 'blur,change'
					}],
					njtype: [{
						required: true,
						message: '请选择检测种类',
						trigger: 'blur,change'
					}],
					njresult: [{
						required: true,
						message: '请选择检测结果',
						trigger: 'blur,change'
					}],
					tquser: [{
						required: true,
						message: '请选择提取人',
						trigger: 'blur,change'
					}],

				},
			}
		},
		watch: {
			photo(nval, oval) {
				this.form.jczp = nval
			},
			//监听检测类型
			ilkresult: {
				handler(nval, oval) {
					let njtype = '',
						njresult = '';
					nval.forEach(i => {
						njtype = `${njtype===''?'':njtype+','}${i.num}`
						njresult = `${njresult ===''?'':njresult+','}${i.result}`
					})
					this.form.njtype = njtype;
					this.form.njresult = njresult;
				},
				deep: true
			},
		},
		onLoad(options) {
			let t = this;
			if (options.mfid) {
				this.form.mfid = options.mfid
				this.form.tid = options.tid ? options.tid : this.form.tid;
				this.form.cid = options.cid ? options.cid : this.form.cid;
				this.form.isqrcode = options.isqrcode ? options.isqrcode : this.form.isqrcode;
				this.formData = {
					mfid: this.form.mfid,
					type: 3
				}
			} else {
				uni.showModal({
					title: '提示',
					content: '用户ID不存在，请稍后再试',
					showCancel: false,
					success() {
						t.goBack()
					}
				})
			}
			//获取人脸识别用户ID
			let checkid = t.$storage.getStorageSync('checkid');
			if(checkid!=this.form.mfid){
				uni.showModal({
					title: '提示',
					content: '未获取到人脸核验信息，请重试',
					showCancel: false,
					success() {
						t.goBack()
					}
				})
			}
			this.getvillages()
			this.getplace()
			this.getdetection()
			this.getilklist()
			this.getposition()

			if (this.timer) {
				clearInterval(this.timer)
			}
			this.timer = setInterval(() => {
				t.form.tqtime = t.$utils.datetime('Y-m-d h:i:s')
			}, 1000)

		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onShow() {
			let t = this;
			if (!t.userinfo) {
				t.$user.getInfo()
			}
		},
		methods: {
			sfnjconfirm(e) {
				this.form.sfnjtext = e[0].label;
				this.form.sfnj = e[0].value;
			},
			sfgtconfirm(e) {
				this.form.sfgttext = e[0].label;
				this.form.isbare= e[0].value;
			},
			userchange(e) {
				let usernames = '';
				e.forEach(i => {
					usernames = `${usernames===''?'':usernames+','}${i}`
				})
				this.form.tquser = usernames;
			},
			setilk(idx, res) {
				let t = this;
				this.ilkresult[idx].result = res
			},

			ilkchange(e) {
				let tempres = this.$utils.deepClone(this.ilkresult);
				this.ilkresult = [];
				e.forEach(i => {
					let old = tempres.find(ilk => ilk.num == i);
					let real = this.ilklist.find(rea => rea.num == i);
					this.ilkresult.push({
						name: real.details,
						num: real.num,
						result: old ? old.result : ''
					})
				})
			},
			save() {

			},
			submit() {
				let t = this;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						// 验证通过
						console.log('验证通过')
						if (t.form.placeid == '172' || t.form.placeid == '100' || t.form.placeid == '99' || t.form
							.placeid == '98') {
							t.form.qyddok = `${t.form.pcaeraname}${t.form.elaeraname}`;
						}
						if (t.form.placeid == '95' || t.form.placeid == '96') {
							t.form.qyddok = ''
						}
						if (t.ilkresult.find(il => il.result === '')) {
							this.$t.message.toast('请完善检测结果')
							return false
						}
						let sfyx = t.ilkresult.filter(il => il.result == 1)
						if (sfyx.length > 0) {
							t.form.sfyx = 1
						}
						t.form.isbare = t.form.isbare ? 1 : 0
						t.form.sfnj = t.form.sfnj ? 1 : 0
						t.add()
					} else {
						// 验证失败
						console.log('验证失败')
					}
				})
			},
			add(param) {
				let t = this;
				this.$t.message.loading('提交中');
				this.$request({
					url: this.$api.hair.add,
					data: t.form,
					method: 'POST'
				}).then(response => {
					t.$t.message.closeLoading();
					if (response.code === 0) {
						let url = `/discoveryPages/hair/list?mfid=${t.form.mfid}`
						//如果有任务ID ，添加完成后则返回主页
						if (t.form.tid) {
							url = `/pages/index`
						}
						//如果是异地任务 添加完返回异地任务列表
						if(t.form.cid){
							url = `/discoveryPages/wait/otherlist`
						}
						uni.showModal({
							title: '',
							content: response.msg,
							showCancel: false,
							success() {
								uni.redirectTo({
									url: url
								});
							}
						});
					} else {
						uni.showModal({
							title: '',
							content: response.msg,
							showCancel: false,
						});
					}
				}).catch((msg) => {
					t.$t.message.closeLoading();
				});
			},

			//扫码
			scancode() {
				let t = this;
				// #ifndef MP-WEIXIN
				this.$jdd.scanCode({
					success(res) {
						t.form.qrcode = res.text
					},
					fail(err) {
						console.log(err)
					}
				})
				// #endif
				//  #ifdef MP-WEIXIN
				// 只允许通过相机扫码
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						t.form.qrcode = res.result
					}
				});
				// #endif
			},


			positionconfirm(e) {
				this.form.qcbw = e[0].label
				this.form.positionid = e[0].value
			},



			tzselect(e) {
				console.log(e)
				this.form.tztime = e.date
			},

			dqconfirm(e) {
				this.form.pcaeraname = `${e.province.label}${e.city.label}${e.area.label}`
			},

			addressconfirm(e) {
				let t = this;
				let guishu = '';
				if (this.userinfo.usergroup == 'jbd' || this.userinfo.usergroup == 'admin') {
					guishu = this.xduser.gsxz
				} else {
					guishu = this.userinfo.guishu
				}
				if ((e[0].value == 95 || e[0].value == 96) && t.userinfo) {
					this.form.qydd = `${guishu.replace('街道','').replace('镇','').replace('乡','')}${e[0].label}`
				} else {
					this.form.qydd = e[0].label
				}
				this.form.placeid = e[0].value
				this.form.qyddok = ''
			},

			cityconfirm(e) {
				this.form.qyddok = e[0].label
				this.form.cityid = e[0].value
			},

			//获取检测地点
			getplace() {
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.place,
					method: 'POST',
					data: {
						//类型 1尿检地点 2走访地点
						type: 3
					}
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.addresslist = response.list;
					}

				}).catch(() => {
					this.$t.message.closeLoading();
				});
			},

			//获取检测种类
			getilklist() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.typelist,
					data: {
						did: 1
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.ilklist = response.list;
						this.ilklist.forEach(i => {
							i.result = ''
						})
					}
					this.$t.message.closeLoading();
				});
			},
			//获取未提取原因
			getnolist() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.typelist,
					data: {
						did: 15
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.nolist = response.list;

					}
					this.$t.message.closeLoading();
				});
			},

			//获取身体部位
			getposition() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.typelist,
					data: {
						did: 7
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.positionlist = response.list;
					}
					this.$t.message.closeLoading();
				});
			},


			//获取村委关联列表
			getvillages() {
				this.$t.message.loading('加载中');
				//获取村委关联列表
				this.$request({
					url: this.$api.common.villages,
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.citylist = response.list;

					}
				});
			},
			//获取人员
			getdetection() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.detection,
					data: {
						mfid: t.form.mfid
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.witness = response.list;
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.box {
		padding: 15rpx;
	}

	.qrcodet {
		color: #b3b3b3;
	}

	.yx {
		padding: 0 20rpx;
		margin: 0 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		border: 1rpx solid #555555;
		border-radius: 10rpx;
		height: 50rpx;
	}

	.nm {
		max-width: 250rpx;
		text-align: right;
		padding-right: 10px;
	}

	.ilkresult {
		display: flex;
		flex-direction: column;
		width: 100%;
		align-items: flex-end;
	}

	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
		height: calc(140rpx + constant(safe-area-inset-bottom));
	}



	.sign {
		width: 100%;
		height: 200rpx;
	}

	.photo {
		width: 100rpx;
		height: 120rpx;
		margin: 10rpx;
	}
</style>